package com.zhizhi.config;

import com.zhizhi.module.synthesizes.dict.entity.Dict;
import com.zhizhi.module.synthesizes.dict.service.DictService;
import io.micrometer.core.instrument.util.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.CommandLineRunner;
import org.springframework.stereotype.Component;

import java.util.*;

@Component
public class DictInitServerRunner implements CommandLineRunner {
    public static final Map<String, Map<Integer, Dict>> DICT_MAP = new HashMap<>();
    @Autowired
    DictService dictService;



    @Override
    public void run(String... args) throws Exception {

        List<Dict> dicts = dictService.list();
        List<String> dictName = new ArrayList<>();
        dicts.forEach(one -> {
            if (!dictName.contains(one.getName())) {
                dictName.add(one.getName());
            }
        });

        dictName.forEach(name -> {
            Map<Integer, Dict> map = new HashMap<>();
            dicts.forEach(dict -> {
                if (Objects.equals(dict.getName(), name)) {
                    map.put(dict.getCode(), dict);
                }
            });
            DICT_MAP.put(name, map);
        });

    }

    /*
     *查詢 字典名称是否有对应的值
     * */
    public static boolean hasDict(String name) {
        return hasDict(name, null);
    }
    /*
     *查詢 字典名称和字典编码是否有对应的值
     * */
    public static boolean hasDict(String name, Integer code) {
        if (StringUtils.isBlank(name)) {
            return false;
        }
        Map<Integer, Dict> dictMap = DICT_MAP.get(name);
        if (dictMap == null) {
            return false;
        }
        if (code != null) {
            return dictMap.containsKey(code);
        }
        return true;
    }
}